#pragma once

#include <iostream>
#include <unistd.h>
#include <string>
#include <cstring>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace hcc;

const uint16_t glocalport = 8888;
const int gsockfd = -1;
enum 
{
    SOCKET_ERROR=1,
    BIND_ERROR
};

// using server_t =std::function<void(int,const std::string &message,InetAddr &who)>;
using server_t = std::function<void(int, const std::string &message, InetAddr &who)>;
class UdpServer
{
public:
    UdpServer(server_t func,uint16_t localport = glocalport)
        : _localport(localport),
          _sockfd(gsockfd),
          _isrunning(false),
          _func(func)
    {
    }
    void InitServer()
    {
        // 1.创建套接字 fd
        _sockfd=::socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            LOG(INFO,"创建套接字失败\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG,"socket create success , _sockfd: %d\n",_sockfd);


        // 2.绑定
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_port=htons(_localport);
        local.sin_addr.s_addr=INADDR_ANY;
        int n=::bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG,"socket bind success \n");
    }
    void Start()
    {
        _isrunning=true;
        char message[1024];
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            ssize_t n=::recvfrom(_sockfd,message,sizeof(message)-1,0,(struct sockaddr*)&peer,&len);
            if(n>0)
            {
                InetAddr addr(peer);
                message[n]=0;
                std::cout<<"[ "<<addr.Ip()<<" : "<<addr.Port()<<" ] : "<<message<<std::endl;
                LOG(DEBUG,"[%s]# %s\n",addr.AddrStr().c_str(),message);
                _func(_sockfd,message,addr);

            }
            else
            {
                LOG(INFO,"recvfrom error\n"); 
            }
        }
    }
    ~UdpServer()
    {
        if(gsockfd<_sockfd) ::close(_sockfd);
    }
private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip;
    bool _isrunning;

    server_t _func;
};